package org.kalai.unifypay.pay;

import java.util.Map;

import org.apache.log4j.Logger;
import org.kalai.unifypay.bean.Member;
import org.kalai.unifypay.bean.Transflow;
import org.kalai.unifypay.mins.MinsPay;
import org.kalai.unifypay.util.CommonUtil;
import org.kalai.unifypay.util.DataDao;
import org.kalai.unifypay.util.ProxyPayUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class Biz2001 implements Biz {
	private static final Logger logger = Logger.getLogger(Biz1007.class);
	@Override
	public Map<String, Object> pay(String tranxSN, long cent, String subject, String notifyUrl, String merchantCode,
			String bizData) {
		if (merchantCode == null) throw new RuntimeException("#211-merchantCode不能为空");
		JSONObject jo = JSON.parseObject(bizData);
		if(jo == null) throw new RuntimeException("#211-bizData不能为空");
		String authCode = jo.getString("authCode");
		if(authCode == null) throw new RuntimeException("#211-authCode不能为空");
		return MinsPay.authPay(tranxSN, merchantCode, authCode, cent/100.0, subject);
	}

	@Override
	public void afterPay(String tranxSN, String respCode, String respDesc, String transAmt) {
		try {
			Transflow transflow = DataDao.getInstance().getTransflow(tranxSN);
			if(transflow == null) {
				logger.error(String.format("交易信息不存在[%s]", tranxSN));
				return;
			}
			if(transflow.getStatus() == 1){//未处理的订单才进行处理
				Member member = DataDao.getInstance().getMember(transflow.getMemberNo());
				if(member == null) {
					logger.error(String.format("商户信息不存在[%s]", transflow.getMemberNo()));
					return;
				}
				boolean isok = "00".equals(respCode);
				//更新交易记录
				DataDao.getInstance().updateTransflow(tranxSN, "", Double.valueOf(Double.valueOf(transAmt)*100).longValue(), isok ? 2 : 3, (Object)respCode, (Object)respDesc);
				if (isok) {
					//异步通知账单系统
					CommonUtil.notifyTransFlow(transflow);
					if (transflow.getBizPattern() == 0) {//D0  添加结算记录 状态为未结算
						String settNo = CommonUtil.generSettNo();
						boolean rs = DataDao.getInstance().addSettlement(tranxSN, settNo, transflow.getBizcode(), member, transflow.getTransAmt() - transflow.getTransFee(), 1);
						if (rs) ProxyPayUtil.proxyPay(settNo, member, ((Double) (transflow.getTransAmt() * 100 - transflow.getTransFee() * 100)).longValue(), transflow.getBizcode(), true);
					}
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

}
